package com.jz.digital.warehousing

import com.jz.digital.MyAppLocation
import com.jz.digital.base.BasePresenter
import com.jz.digital.bean.BaseEntity
import com.jz.digital.bean.ServerBean
import com.jz.digital.listener.ApiCallback
import com.jz.digital.net.DataApi
import com.jz.digital.utils.AccountManagerHelper
import com.jz.digital.utils.AppUtil
import com.jz.digital.utils.ErrorCode
import com.jz.digital.utils.GreenDaoUtils
import com.jz.digital.utils.GsonUtil
import com.jz.digital.utils.LogUtils
import java.util.concurrent.CountDownLatch

/**
 * @author WangYong
 * @date 2024/11/28 13:27
 * @description:生产入库
 */
class ProductionWarehousingPresenter : BasePresenter<IProductionWarehousingView>() {
    private val tag = "ProductionWarehousingPresenter"
    val mCangBieList = mutableListOf<ServerBean.GXInfo>()
    val mBanZuList = mutableListOf<ServerBean.GXInfo>()
    val mBuLiangList = mutableListOf<ServerBean.GXInfo>()
    private val mCountDown = CountDownLatch(2)
    fun initData() {
        view?.showLoading()
        getBanZuFromServer()
        getCangBieFromServer()
    }

    private fun getBanZuFromServer() {
        LogUtils.d(tag, "班组-开始从服务器获取工艺列表")
        DataApi.api.getGXInfo(ServerBean.GXInfoRequest(mode = 1, type = "BZ"))
            .enqueue(object : ApiCallback<BaseEntity<List<ServerBean.GXInfo>?>>() {
                override fun onSuccess(response: BaseEntity<List<ServerBean.GXInfo>?>?) {
                    LogUtils.d(tag, "班组列表获取成功 response=${GsonUtil.toJson(response)}")
                    if (response != null && !response.data.isNullOrEmpty()) {
                        mBanZuList.addAll(response.data!!)
                    }
                    typeLoadFinish()
                }

                override fun onError(t: Throwable?, code: Int, message: String?) {
                    LogUtils.d(
                        tag,
                        "工序列表获取失败 error=${t?.message},code=$code,message=$message"
                    )
                    typeLoadFinish()
                }

            })
    }

    /**
     * 仓别
     */
    private fun getCangBieFromServer() {
        LogUtils.d(tag, "仓别-开始从服务器获取工艺列表")
        DataApi.api.getGXInfo(ServerBean.GXInfoRequest(mode = 1, type = "CB"))
            .enqueue(object : ApiCallback<BaseEntity<List<ServerBean.GXInfo>?>>() {
                override fun onSuccess(response: BaseEntity<List<ServerBean.GXInfo>?>?) {
                    LogUtils.d(tag, "仓别列表获取成功 response=${GsonUtil.toJson(response)}")
                    if (response != null && !response.data.isNullOrEmpty()) {
                        mCangBieList.addAll(response.data!!)
                    }
                    typeLoadFinish()
                }

                override fun onError(t: Throwable?, code: Int, message: String?) {
                    LogUtils.d(
                        tag,
                        "仓别列表获取失败 error=${t?.message},code=$code,message=$message"
                    )
                    typeLoadFinish()
                }

            })
    }

    fun getBuLiangFromServer() {
        LogUtils.d(tag, "不良-开始从服务器获取不良列表")
        if (mBuLiangList.isNotEmpty()) {
            view.onBuLiangSuccess()
            return
        }
        view.showLoading()
        DataApi.api.getGXInfo(ServerBean.GXInfoRequest(mode = 2, type = "BL"))
            .enqueue(object : ApiCallback<BaseEntity<List<ServerBean.GXInfo>?>>() {
                override fun onSuccess(response: BaseEntity<List<ServerBean.GXInfo>?>?) {
                    LogUtils.d(tag, "工序-不良列表获取成功 response=${GsonUtil.toJson(response)}")
                    if (response != null && !response.data.isNullOrEmpty()) {
                        mBuLiangList.addAll(response.data!!)
                        view.onBuLiangSuccess()
                    }
                    typeLoadFinish()
                }

                override fun onError(t: Throwable?, code: Int, message: String?) {
                    LogUtils.d(
                        tag,
                        "工序-不良列表获取失败 error=${t?.message},code=$code,message=$message"
                    )
                    typeLoadFinish()
                }
            })
    }

    fun commit(
        barcode: String,
        no1: String,
        no9: String,
        no7: String,
        no8: String,
        no10: String,
        qty2: Int,
        qty3: Int, qty4: Int, no6: String, isCommit: Boolean = false
    ) {
        val userInfo = GreenDaoUtils.getUserInfo(AccountManagerHelper.getInstance().userId)
        if (userInfo == null) {
            LogUtils.d(tag, "用户信息为空")
            return
        }
        view?.showLoading()
        val request = ServerBean.RuKuRequest(
            mode = 3,
            barcode = barcode,
            wk_id = userInfo.userId,
            wk_name = userInfo.userName,
            pda = AppUtil.getIMEI(MyAppLocation.mContext),
            no1 = no1,
            no6 = no6,
            no9 = no9,
            no10,
            no7,
            no8,
            qty2,
            qty3,
            qty4
        )
        LogUtils.d(tag, "生产入库 request=${GsonUtil.toJson(request)}")
        DataApi.api.rukuReport(
            request
        ).enqueue(object : ApiCallback<BaseEntity<ServerBean.RuKuResponse?>>() {
            override fun onSuccess(response: BaseEntity<ServerBean.RuKuResponse?>?) {
                LogUtils.d(tag, "生产入库成功 response=${GsonUtil.toJson(response)}")
                view?.dismissLoading()
                if (response != null){
                    if (response.code == ErrorCode.CODE_NOT_ALLOW_SIMULTANEOUS_RECEIPT) {
                        view?.reportFailed(isCommit,response.message ?: "")
                        return
                    }
                    if (response.data != null) {
                        view?.reportSuccess(response.data!!, isCommit)
                    } else {
                        view?.reportFailed(isCommit)
                    }
                }

            }

            override fun onError(t: Throwable?, code: Int, message: String?) {
                LogUtils.d(tag, "生产入库异常 error=${t?.message},code=$code,message=$message")
                view?.dismissLoading()
                view?.reportFailed(isCommit, message)
            }
        })
    }

    fun getBanZuTitle(basId: String): String {
        val result = mBanZuList.firstOrNull { it.basId == basId }
        return if (result != null && !result.basName.isNullOrEmpty()) result.basName
            ?: basId else basId
    }

    fun getCangBieTitle(basId: String): String {
        val result = mCangBieList.firstOrNull { it.basId == basId }
        return if (result != null && !result.basName.isNullOrEmpty()) result.basName
            ?: basId else basId
    }

    private fun typeLoadFinish() {
        mCountDown.countDown()
        if (mCountDown.count == 0L) {
            view?.dismissLoading()
        }
    }
}